package com.wf.messageBoard.service.local.impl;


import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wf.apicommons.entity.MessageBoard.LeavingAMessage;
import com.wf.apicommons.entity.MessageBoard.MqMessage;
import com.wf.apicommons.entity.articleManagement.ArticleDetails;
import com.wf.apicommons.entity.chatManagement.ChatRecord;
import com.wf.apicommons.entity.userManagement.UserInformation;
import com.wf.apicommons.utils.*;
import com.wf.apicommons.config.RabbitConstant;
import com.wf.messageBoard.mapper.LeavingAMessageMapper;
import com.wf.messageBoard.service.call.ChatFeignService;
import com.wf.messageBoard.service.local.MessageBoardService;
import io.seata.spring.annotation.GlobalTransactional;
import jdk.nashorn.internal.ir.annotations.Reference;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;


/**
 * @Description: 留言service实现类
 */
@Service
@Slf4j
public class MessageBoardServiceImpl implements MessageBoardService {

    @Autowired
    LeavingAMessageMapper crm;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    RedisUtils redisUtils;

    @Resource
    ChatFeignService chatFeignService;

    /**
     * 将博客数据退送至MQ
     * @param data
     * @return
     */
    @Override
    public CommonResult<String> pushBlogDataService(MqMessage<ArticleDetails> data) {
        //将数据推送至MQ
        rabbitTemplate.convertAndSend(RabbitConstant.ES_EXCHANGE, RabbitConstant.ES_ROUTING_KEY, JSONUtil.toJsonStr(data));
        return CommonResult.success("推送成功");
    }


    /**
     * 将留言数据退送至MQ
     * @param data
     * @return
     */
    @Override
    public CommonResult<String> pushLeavingAMessageDataService(MqMessage<LeavingAMessage> data) {

        LeavingAMessage leavingAMessage=JSONUtil.toBean(data.getJsonData(),LeavingAMessage.class);
        UserInformation commenterId = leavingAMessage.getCommenterId();
        UserInformation recipientId = leavingAMessage.getRecipientId();
        Integer type = leavingAMessage.getType();
        String content = leavingAMessage.getContent();
        if(type!=null&&StrUtil.isNotBlank(content)&&commenterId!=null&& StrUtil.isNotBlank(commenterId.getID())&&recipientId!=null&& StrUtil.isNotBlank(recipientId.getID())){
            leavingAMessage.setID(SnowflakeUtil.getID());
            leavingAMessage.setReadStatus(0);

            //插入留言记录
            if(crm.insertLeavingAMessage(leavingAMessage)>0){
                //将数据推送至MQ
                rabbitTemplate.convertAndSend(RabbitConstant.LEAVING_A_MESSAGE_EXCHANGE, RabbitConstant.LEAVING_A_MESSAGE_ROUTING_KEY, JSONUtil.toJsonStr(data));
                return CommonResult.success("推送成功");
            }
        }
        return CommonResult.fail(CodeEnum.ILLEGAL_PARAMETER);
    }


    /**
     * 查询留言消息未读数量
     * @param userId
     * @return
     */
    @Override
    public CommonResult<List<Map<String,Object>>> queryLeavingAMessageUnreadQuantity(String userId){
        if(StrUtil.isNotBlank(userId)){
           return CommonResult.success(crm.selectLeavingAMessageUnreadQuantity(userId));
        }
        return CommonResult.fail(CodeEnum.ILLEGAL_PARAMETER);
    }

    /**
     * 修改留言消息读取状态
     * @param param
     * @return
     */
    @Override
    public CommonResult<String> updateLeavingAMessageReadStatus(Map<String,Object> param){
        String userId=MapUtil.getStr(param,"userId");
        String type = MapUtil.getStr(param, "type");
        if(StrUtil.isNotBlank(userId)&&StrUtil.isNotBlank(type)){
            UpdateWrapper updateWrapper=new UpdateWrapper();
            updateWrapper.eq("recipient_id",userId);
            updateWrapper.eq("type",type);
            updateWrapper.set("read_status",1);
            return CommonResult.success(crm.update(null,updateWrapper)>0?"成功":"失败");
        }
        return CommonResult.fail(CodeEnum.ILLEGAL_PARAMETER);
    }


    /**
     * 查询留言列表
     * @param param
     * @return
     */
    @Override
    public CommonResult<Page<Map<String,Object>>> queryLeavingAMessageList(Map<String,Object> param){
        Integer page=MapUtil.getInt(param,"page",1);
        Integer size=MapUtil.getInt(param,"size",10);
        Integer type=MapUtil.getInt(param,"type",0);
        String  userId=MapUtil.getStr(param,"userId");

        if(type!=null&&StrUtil.isNotBlank(MapUtil.getStr(param,"userId"))&&page>0&&size>0){
            Page<Map<String,Object>> queryPage=new Page<>(page,size);
            return  CommonResult.success(crm.selectLeavingAMessageList(queryPage, param));
        }
        return CommonResult.fail(CodeEnum.ILLEGAL_PARAMETER);
    }

    /**
     * 处理好友验证消息
     * @param param
     * @return
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public CommonResult<String>  processFriendApplication(Map<String,Object> param){
        try{
            String leavingAMessageId=MapUtil.getStr(param,"leavingAMessageId");
            Integer applyWhetherAdopt=MapUtil.getInt(param,"applyWhetherAdopt");
            String commenterId=MapUtil.getStr(param,"commenterId");
            String recipientId=MapUtil.getStr(param,"recipientId");
            String nickName=MapUtil.getStr(param,"nickName");
            String avatarLink=MapUtil.getStr(param,"avatarLink");
            if(StrUtil.isNotBlank(leavingAMessageId)&&applyWhetherAdopt!=null&&StrUtil.isNotBlank(commenterId)&&StrUtil.isNotBlank(recipientId)){
                //判断是否通过了好友申请--已通过
                if(applyWhetherAdopt==1){
                    ChatRecord chatRecord=new ChatRecord();
                    UserInformation userInformation = new UserInformation();
                    userInformation.setID(recipientId).setNickName(nickName).setAvatarLink(avatarLink);
                    chatRecord.setSenderId(userInformation)
                            .setRecipientId(commenterId)
                            .setMessageContent("我以通过了你的好友申请，快来和我聊天吧~")
                            .setReadStatus(0)
                            .setIsInitializationContent(1)
                            .setType(0)
                    ;
                    String pushMsg=JSONUtil.toJsonStr(MqMessage.setMessageTypeAndData(chatRecord,MqMessage.MESSAGE_TYPE_CHAT));
                    //远程调用聊天微服务，推送验证通过消息
                    chatFeignService.pushLeavingAMessageData(pushMsg);
                }
                //修改留言操作状态
                crm.updateLeavingAMessageIsOperation(param);
                //修改好友验证状态
                crm.updateFriendsRelationshipApplyWhetherAdopt(param);

                return  CommonResult.success("成功");
            }
            return CommonResult.fail(CodeEnum.ILLEGAL_PARAMETER);
        }catch (Exception e){
            log.info("处理好友验证消息错误：{}",e.getMessage());
            throw  e;

        }

    }
}
